import { injectable, inject } from 'inversify';
import { IRepository } from './interfaces/IRepository';
import { Session } from '../../../domain/entities/session.entity';
import { DataSource, Repository } from 'typeorm';
import { TYPES } from '../../ioc/types';

@injectable()
export class SessionRepository implements IRepository<Session> {
  private repository: Repository<Session>;

  constructor(@inject(TYPES.DataSource) private dataSource: DataSource) {
    this.repository = dataSource.getRepository(Session);
  }

  async save(entity: Session): Promise<Session> {
    return this.repository.save(entity);
  }

  async findById(id: string): Promise<Session | null> {
    return this.repository.findOneBy({ id });
  }

  async findOne(options: any): Promise<Session | null> {
    return this.repository.findOne(options);
  }

  async find(options?: any): Promise<Session[]> {
    return this.repository.find(options || {});
  }

  async delete(id: string): Promise<void> {
    await this.repository.delete(id);
  }

  async findByParticipant(userId: string): Promise<Session[]> {
    let SS = Session;
    return this.dataSource.getRepository(SS).createQueryBuilder('session')
      .where(':userId = ANY(session.participants)', { userId })
      .getMany();
  }
}